package com.hmall.trade.listener;


import com.hmall.api.client.PayClient;
import com.hmall.api.domain.dto.PayOrderDTO;
import com.hmall.trade.constans.MqConstance;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final PayClient payClient;
    private final IOrderService orderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstance.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstance.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MqConstance.DELAY_ORDER_KEY
    ))
    public void ListenerDelayMessage(Long orderId){
        //本地查询确认是否已经修改状态并做健壮性判断
        Order order = orderService.getById(orderId);
        if(order == null || order.getStatus() != MqConstance.ORDER_UNPAID_STATUS){
            return;
        }
        //远程调用支付服务查询支付状态
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        if(payOrderDTO != null &&payOrderDTO.getStatus() ==MqConstance.PAY_PAID_STATUS){
            //已支付，标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
        }else {
            //未支付，取消订单，恢复库存
            orderService.cancelOrder(orderId);
        }


    }

}
